package com.cooper.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 密码密文生成器
 * 密码加密采用单向方式, 采用MD5和DES混合交叉的办法
 * @Title: PasswordGeneration.java<br>
 * @Date: Dec 28, 2011 2:28:12 PM<br>
 * @Copyright (c) 2011 MiXuan <br> * 
 * @since 1.0
 * @author coraldane
 */
public class PasswordGeneration {
	
	private static Logger log = LoggerFactory.getLogger(PasswordGeneration.class);
	
	public static String md5(String text) {
		String strEncrypt = null;
		if(StringUtils.isEmpty(text)){
			return null;
		}
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(text.getBytes());
			strEncrypt = Des.byte2Hex(md5.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
		return strEncrypt;
	}
	
	public static String encrypt(String text) throws Exception{
		if(StringUtils.isEmpty(text)){
			return new Des().decode("123456789abCdefg");
		}
		StringBuffer buffer = new StringBuffer();
		String strMd5 = md5(text);
		int first = Integer.parseInt(strMd5.substring(0,1), 16)+3;
		//将MD5密文中取4位字符作为密钥生成DES密码(截取密钥的开始位置为密文的首字符的整型值+3)
		String key = strMd5.substring(first+2, first+6);
		String strDes = new Des(key).encode(text);
		int end = Integer.parseInt(strDes.substring(strDes.length()-1), 16);
		int pos = Integer.parseInt(strMd5.substring(end,end+1), 16);
		buffer.append(strMd5.substring(0,pos))
			.append(strDes.substring(0,end+1))
			.append(strMd5.substring(end, strMd5.length()));
		log.trace("text:" + text + ",encrypt:" + buffer);
		return buffer.toString();
	}
	
	public static void main(String[] args) throws Exception{
		String password = "mixuan629";
//		String str = "e727ec21779aafdb9d2a5e1fc94abf51";
		String str = "e727ec2170a0d53fa2354109aafdb9d2a5e1fc94abf51";
		System.out.println(str.length());
		//MD5: e727ec21779aafdb9d2a5e1fc94abf51
		
		System.out.println(encrypt(password));
	}
	
}

